package main

import (
	"fmt"
	"sort"
)

/*
*
看到256页
*/
func main() {
	fmt.Println("==Map练习===")
	// 创建一个map
	var map1 map[string]int
	/* 参数1:类型,参数2:初始分配空间 */
	map1 = make(map[string]int, 10)
	/* 添加数据 */
	map1["张三"] = 18
	map1["李四"] = 20
	map1["王五"] = 22
	/* 遍历map */
	fmt.Println("map1:=", map1)

	/* 创建一个map2 */
	map2 := map[string]int{
		"张三": 18,
		"李四": 20,
		"王五": 22,
	}
	fmt.Println("map2:=", map2)
	fmt.Println("map2:=", map2)
	fmt.Println("map2{张三}", map2["张三"])

	/* 删除元素 */
	delete(map1, "张三")
	fmt.Println("删除后:map1:=", map1)

	/* 查看 */
	value, ok := map1["李四"]
	fmt.Println("李四的年龄:", value, "存在吗?", ok)

	/* 遍历map */
	for key, value := range map1 {
		fmt.Printf("map1,key:%v, value: %v\n", key, value)
	}

	/* map长度 */
	fmt.Println("map1的长度:", len(map1))

	/* 声明一个切片,它是一个List或者数组,里面放的元素是Map,切片可以动态扩容 */
	var map3 []map[string]int
	map3 = make([]map[string]int, 2)
	if map3[0] == nil {
		map3[0] = make(map[string]int)
		map3[0]["张三"] = 18
	}

	maptemp := make(map[string]int)
	maptemp["a"] = 20
	map3 = append(map3, maptemp)
	fmt.Println("map3:=", map3)
	fmt.Println("遍历map切片")

	for i, m := range map3 {
		for key, value := range m {
			fmt.Printf("遍历:map3[%d],key:%v, value: %v\n", i, key, value)
		}
	}

	fmt.Println("==map排序==")
	var map4 map[int]string
	map4 = make(map[int]string)
	map4[100] = "a"
	map4[20] = "b"
	map4[30] = "c"
	map4[200] = "d"
	map4[150] = "e"

	var keys []int
	for key, value := range map4 {
		fmt.Printf("map4,key:%v, value:%v \n", key, value)
		keys = append(keys, key)
	}

	/* map排序,只能排序key */
	sort.Ints(keys)
	fmt.Println("排序后的keys:", keys)

	for _, key := range keys {
		fmt.Printf("排序后:map4,key:%v, value:%v \n", key, map4[key])
	}
}
